package org.fatmansoft.teach.controllers;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.openhtmltopdf.extend.FSSupplier;
import com.openhtmltopdf.extend.impl.FSDefaultCacheStore;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.fatmansoft.teach.Repository.ViewRepository.StudentRepository;
import org.fatmansoft.teach.entity.ViewEntity.Student;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.util.GetStudentFullInfo;
import org.fatmansoft.teach.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.validation.Valid;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/basicInfo")
public class BasicInfoController {
    @Autowired
    StudentRepository studentRepository;  //从容器中注入repository

    @Autowired
    private ResourceLoader resourceLoader;
    private FSDefaultCacheStore fSDefaultCacheStore = new FSDefaultCacheStore();

    @Autowired
    private GetStudentFullInfo getStudentFullInfo;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //    获取后端数据的接口
    @PostMapping("/getInfo")  //设置后端接口
    public DataResponse getInfo(@Valid @RequestBody DataRequest request) {  //request为前端传入的参数（分页的页码和学生学号）
        Map<String, Object> map = new HashMap<>(); // 该map用于储存后端返回的数据

//        以下两个变量对应前端传入的两个变量，对变量进行接受
        int currentPage = 1;  //分页页码
        String RequestCurPage = Utils.parseRequest(request, "currentPage", map);  //获取解析的数据
        if (RequestCurPage != null & Utils.checkNum(RequestCurPage)) {  //要求数据不为空，且为纯数字
            currentPage = Integer.parseInt(RequestCurPage);
        }

        String id = "";  //学号
        String RequestId = Utils.parseRequest(request, "id", map);  //获取解析的数据
        if (RequestId != null) {  //要求数据不为空
            id = RequestId;
        }

//        分页查询
        List<Student> studentList = new ArrayList<>();  //创建学生列表，用于返回前端
        if (!id.equals("")) {  //按照id查询
            if (studentRepository.findById(Integer.parseInt(id)).isPresent()) {  //如果当前学号存在(精确查询)
                studentList.add(studentRepository.findById(Integer.parseInt(id)).get());
            }
        } else {  //不按照学号查询
            studentList = studentRepository.findAll(PageRequest.of(currentPage - 1, 5)).toList();
        }

        map.put("tableData", studentList);  //返回的列表数据
        map.put("total", studentRepository.findAll().size());  //返回数据的总条数

        return new DataResponse("0", map);  //code:0表示当前返回正常
    }

    //    删除数据的后端接口
    @PostMapping("/deleteInfo")
    public DataResponse delete(@Valid @RequestBody DataRequest request) {  //接受前端传入的deleteId数据
        Map<String, Object> map = new HashMap<>();  // 该map用于储存后端返回的数据

        int deleteId = 0;  //该变量用于接受前端的deleteId数据
        String RequestData = Utils.parseRequest(request, "deleteId", map);  //获取解析的数据
        if (RequestData != null & Utils.checkNum(RequestData)) {  //要求数据不为空，且为纯数字
            deleteId = Integer.parseInt(RequestData);
        }

        studentRepository.deleteById(deleteId);  //删除对应ID的学生

        return new DataResponse("0", map);
    }

    //    数据更新和新增的后端接口
    @PostMapping("/updateAndCreateInfo")
    public DataResponse updateAndCreate(@Valid @RequestBody DataRequest request) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        String code;

//        从前端获取formData转化为Map
        Map formData = (Map) request.getData().get("formData");
        Student student = new Student();
        if (formData.get("id") != null) student.setId(Integer.parseInt(formData.get("id").toString()));
        if (formData.get("studentName") != null) student.setStudentName(formData.get("studentName").toString());
        if (formData.get("sex") != null) student.setSex(formData.get("sex").toString());
        if (formData.get("cellPhone") != null) student.setCellPhone(formData.get("cellPhone").toString());
        if (formData.get("birthday") != null)
            student.setBirthday(sdf.parse(formData.get("birthday").toString() + " 00:00:00"));  //获取生日
        if (formData.get("age") != null) student.setAge(Integer.parseInt(formData.get("age").toString())); //获取年龄
        if (formData.get("address") != null) student.setAddress(formData.get("address").toString());

//        判断当前元组是否已经存在（根据学号是否存在)
        if (studentRepository.findById(student.getId()).isPresent()) {  //查看id是否已经存在
            code = "0"; //表示更新
        } else {
            code = "1"; //表示新增
        }

        studentRepository.save(student);  //更新/保存的数据

        return new DataResponse(code, map);
    }

    //    下列方法用来生成学生pdf简历
    public ResponseEntity<StreamingResponseBody> getPdfDataFromHtml(String htmlContent) {  //传入html内容
        try {
//            创建builder
            PdfRendererBuilder builder = new PdfRendererBuilder();
//            传入html内容
            builder.withHtmlContent(htmlContent, null);
//            参数配置
            builder.useFastMode();
            builder.useCacheStore(PdfRendererBuilder.CacheStore.PDF_FONT_METRICS, fSDefaultCacheStore);
//            获取字体资源
            Resource resource = resourceLoader.getResource("classpath:font/SourceHanSansSC-Regular.ttf");
            InputStream fontInput = resource.getInputStream();
            builder.useFont(new FSSupplier<InputStream>() {
                @Override
                public InputStream supply() {
                    return fontInput;
                }
            }, "SourceHanSansSC");
//            设置返回流主体
            StreamingResponseBody stream = outputStream -> {
                builder.toStream(outputStream);
                builder.run();
            };
//            返回值类型为PDF
//            响应体为stream的内容
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_PDF)
                    .body(stream);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    @PostMapping("/getStudentIntroducePdf")
    public ResponseEntity<StreamingResponseBody> getStudentIntroducePdf(@Valid @RequestBody DataRequest request) throws ParseException {
        int studentId = 0;  //该变量用于接受前端的deleteId数据
        String RequestData = Utils.parseRequest(request, "studentId", null);  //获取解析的数据
        if (RequestData != null & Utils.checkNum(RequestData)) {  //要求数据不为空，且为纯数字
            studentId = Integer.parseInt(RequestData);
        }

        Map<String, Object> data = getStudentFullInfo.getStudentFullInfo(studentId);  //获取data数据

        String content = "<!DOCTYPE html>";
        content += "<html>";
        content += "<head>";
        content += "<style>";
        content += "html { font-family: \"SourceHanSansSC\", \"Open Sans\";}";
        content += "</style>";
        content += "<meta charset='UTF-8' />";
        content += "<title>学生简历pdf预览</title>";
        content += "</head>";

//        获取学生姓名和其他数据
        String studentName = (String) data.get("studentName");
        Integer theStudentId = (Integer) data.get("studentId");
        List<Map<String, Object>> fullInfoList = (List) data.get("fullInfoList");

        content += "<body>";
        content += "<table style='width: 100%;'>";
        content += "   <thead >";
        content += "     <tr style='text-align: center;font-size: 32px;font-weight:bold;'>";
        content += "       学号:" + theStudentId + " </tr>";
        content += "     <tr style='text-align: center;font-size: 32px;font-weight:bold;'>";
        content += "        姓名:" + studentName + " </tr>";
        content += "   </thead>";
        content += "   </table>";

        for (int i = 0; i < fullInfoList.size(); i++) {  //遍历附加信息列表,获取所有学生信息
            content += "<table style='width: 100%;border-collapse: collapse;border: 1px solid black;'>";
            content += " <tbody>";
            content += "     <tr style='text-align: center;border: 1px solid black;font-size: 26px;'>";
            content += "      " + fullInfoList.get(i).get("title") + " ";
            content += "     </tr>";
//            使用json实现简历数据的传输
            List<String> jsonStr = (List<String>) fullInfoList.get(i).get("content");
            for (int m = 0; m < jsonStr.size(); m++) {
                JSONObject json = JSONObject.parseObject(jsonStr.get(m), Feature.OrderedField);
                for (Map.Entry<String, Object> entry : json.entrySet()) {
                    content += "     <tr style='text-align: center;border: 1px solid black; font-size: 12px;'>";
                    content += "            " + entry.getKey() + entry.getValue() + " ";
                    content += "     </tr>";
                }
                if(m!= jsonStr.size()-1){
                content += "     <tr>";
                content += "     <hr style='width:60%' />";
                content += "     </tr>";}
            }
            content += " </tbody>";
            content += "   </table>";
        }

        content += "</body>";
        content += "</html>";
        return getPdfDataFromHtml(content);
    }
}
